﻿using System;
using System.Xml;

namespace Douya.Json
{
    public class XmlWriter
    {
        public string Write(string RootName, JsonObject JsonObj)
        {
            XmlDocument dom = new XmlDocument();
            WriteObject(dom.AppendChild(dom.CreateElement(RootName)), JsonObj);
            return dom.OuterXml;
        }

        void WriteObject(XmlNode parent, JsonObject JsonObj)
        {
            foreach (String name in JsonObj.Keys)
            {
                IJsonValue value = JsonObj.GetValue(name);
                if (value.Type == ValueType.TypeObject)
                {
                    WriteObject(parent.AppendChild(parent.OwnerDocument.CreateElement(name)), (JsonObject)value);
                }
                else if (value.Type == ValueType.TypeArray)
                {
                    WriteArray(parent, name, (JsonArray)value);
                }
                else
                {
                    parent.AppendChild(parent.OwnerDocument.CreateElement(name)).InnerText = value.GetString();
                }
            }
        }

        void WriteArray(XmlNode parent, String NodeName, JsonArray JsonAry)
        {
            for (int i = 0; i < JsonAry.Count; ++i)
            {
                IJsonValue value = JsonAry.GetValue(i);
                if (value.Type == ValueType.TypeObject)
                {
                    WriteObject(parent.AppendChild(parent.OwnerDocument.CreateElement(NodeName)), (JsonObject)value);
                }
                else if (value.Type == ValueType.TypeArray)
                {
                    //
                }
                else
                {
                    parent.AppendChild(parent.OwnerDocument.CreateElement(NodeName)).InnerText = value.GetString();
                }
            }
        }
    }
}
